package com.qualityevaluationclouduser.service.impl;

import com.qualityevaluationclouduser.entity.EmaiAauth;
import com.qualityevaluationclouduser.repository.EmaiAauthRepository;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
@Data
@Slf4j
@Async
@Component
@Transactional
public class EmailService {
    //发件人地址
    @Value("${email.senderAddress}")
    public static String senderAddress;// = "xxx@163.com";
    //发件人账户名
    @Value("${email.senderAccount}")
    public  String senderAccount;// = "xxx";
    //发件人账户密码
    @Value("${email.senderPassword}")
    public  String senderPassword;// = "xxx";
    //SMTP服务器地址
    @Value("${email.SMTP.smtHost}")
    private  String smtHost;// = "SMTP服务器地址";
    @Autowired
    EmaiAauthRepository emaiAauthRepository;

    /**
     * @param message            需要发送的消息
     * @param receiveMailAccount 接受人邮箱地址
     * @throws Exception
     */
//    public void senEmail(String message, String receiveMailAccount) throws Exception {
//        try {
//            Properties props = new Properties();
//            //设置用户的认证方式
//            props.setProperty("mail.smtp.auth", "true");
//            //设置传输协议
//            props.setProperty("mail.transport.protocol", "smtp");
//            //设置发件人的SMTP服务器地址
////            props.setProperty("mail.smtp.host", smtHost);
//            Session session = Session.getInstance(props);
//            session.setDebug(true);
//            Message msg = getMimeMessage(session, message, receiveMailAccount);
//            Transport transport = session.getTransport();
//            transport.connect(smtHost,senderAccount, "ktltqvqvzixqhgbg");
//            transport.sendMessage(msg, msg.getAllRecipients());
//            //关闭邮件连接
//            transport.close();
//            //保存至数据库
//            EmaiAauth emaiAauth = new EmaiAauth();
//            emaiAauth.setEmailCode(message);
//            emaiAauth.setEmailCate(new Date());
//            emaiAauth.setEmailAddress(receiveMailAccount);
//            emaiAauthRepository.save(emaiAauth);
//        }catch (RuntimeException e){
//            throw new RuntimeException(e.getMessage());
//        }
//
//    }

    /**
     * 获得创建一封邮件的实例对象
     *
     * @param session
     * @return
     */
//    public static MimeMessage getMimeMessage(Session session, String message, String recipientAddress) throws Exception {
//        //1.创建一封邮件的实例对象
//        MimeMessage msg = new MimeMessage(session);
//        msg.setFrom(new InternetAddress("1577082050@qq.com"));
//        /**
//         * 3.设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
//         * MimeMessage.RecipientType.TO:发送
//         * MimeMessage.RecipientType.CC：抄送
//         * MimeMessage.RecipientType.BCC：密送
//         */
//        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
//        //设置邮件主题
//        msg.setSubject("验证码", "UTF-8");
//        //下面是设置邮件正文
//        msg.setContent(message, "text/html;charset=UTF-8");
//        msg.setSentDate(new Date());
//
//        return msg;
//    }

    /**
     * 构造邮箱发送服务
     * @param message 消息内容
     * @param receiveMailAccount 发送对象
     * @throws MessagingException
     */
    public void senEmailSpring(String message, String receiveMailAccount) throws MessagingException {
        try {
            // 发送器
            JavaMailSenderImpl sender = new JavaMailSenderImpl();
            sender.setHost(smtHost);
            sender.setPort(25); // 默认就是25
            sender.setUsername(senderAccount);
            sender.setPassword(senderPassword);
            sender.setDefaultEncoding("UTF-8");

            // 配置文件对象
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true"); // 是否进行验证
            Session session = Session.getInstance(props);
            sender.setSession(session); // 为发送器指定会话

            MimeMessage mail = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mail);
            helper.setTo(receiveMailAccount); // 发送给谁
            helper.setSubject("验证码"); // 标题

            helper.setFrom(new InternetAddress(senderAccount)); // 来自
            // 邮件内容，第二个参数指定发送的是HTML格式
            helper.setText("<font color='red'>"+message+"</font>",true);
            sender.send(mail); // 发送

            EmaiAauth emaiAauth = new EmaiAauth();
            emaiAauth.setEmailCode(message);
            emaiAauth.setEmailCate(new Date());
            emaiAauth.setEmailAddress(receiveMailAccount);
            emaiAauthRepository.save(emaiAauth);
            log.info("sending-email-code-success");
        }catch (RuntimeException e){
            throw new RuntimeException(e.getMessage());
        }

    }
}
